<?php
/**
 * Silverstripe cms tree  Extension
 * Powered by jQuery & Plugins at the jsparty folder
 * @author rgodinho
 */
class SSCustomTreeListExtension extends Extension {
  	  	
	function extraStatics() {
    return array(
    );
  }

  public function Subject() {
    return $this->owner;
  }

  /**
   * Render a template
   * @param $template template_file
   * @return html render
   */
  public function Template($template) {
    return $this->owner->renderWith($template);
  }

   /**
   * Render Tree
   * @return html rendered
   */
  public function getSSCustomTreeList() {
    // -- jQuery Files at jsparty folder
	Requirements::javascript('jsparty/jquery/plugins/treeview/lib/jquery.js');
	Requirements::javascript('jsparty/jquery/plugins/treeview/jquery.treeview.js');

	// -- Extension css file
  	$this->includePluginsCss('sscustomtreelist.css');
    
    // -- jsparty jquery plugins css 
  	$this->includePluginsCss('jquery.treeview.css');
    
	// -- Javascript for the tree    
	Requirements::customScript(<<<JS
    	JQ = jQuery.noConflict();
    		
		JQ(document).ready(function(){
		JQ("#browser").treeview({
			toggle: function() {
			JQ(this).find(">span").text();
			}
		});
	});
JS
    );    
        
    return $this->owner->renderWith('TreeCss');
  }
  
  /**
   * include a css, check first in the the theme, then project, in the module or jsparty treeview
   * @param $css
   * @return void
   */
  private function includePluginsCss( $css ) {
    if( Director::fileExists($file = project() . '/themes/' . SSViewer::current_theme() . '/css/' . $css) ) {
      Requirements::css($file);

    }
    elseif( Director::fileExists($file = project() . '/css/' . $css) ) {
      Requirements::css($file);
    }
    elseif( Director::fileExists($file = SSCUSTOMTREELIST . '/css/' . $css) )  {    	
      Requirements::css(SSCUSTOMTREELIST . '/css/' . $css);
    }
    else {
    	// --  Look for jsparty the css files
    	if ( Director::fileExists(JQUERY_PLUNGIN_TREEVIEW . $css)) {
    		Requirements::css(JQUERY_PLUNGIN_TREEVIEW . $css);
    	}
    }
  }  
}